package com.zy.dsms.shiro.realm;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.zy.dsms.pojo.Permission;
import com.zy.dsms.pojo.Role;
import com.zy.dsms.pojo.User;
import com.zy.dsms.service.UserService;
public class AuthRealm extends AuthorizingRealm{
 
	@Autowired
	private UserService userService;
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
		//获取session中的用户
		User user = (User) principal.fromRealm(this.getClass().getName()).iterator().next();
		//定义list集合用于存放当前用户的权限集合
		List<String> permissionList = new ArrayList<String>();
		List<String> rolesList = new ArrayList<String>();
		Set<Role> roles = user.getRoles();
		if(roles.size() > 0){
			for (Role role : roles) {
				rolesList.add(role.getRoleName());
				Set<Permission> permissions = role.getPermissions();
				if(permissions.size() > 0){
					for (Permission permission : permissions) {
						permissionList.add(permission.getPermissionName());
					}
				}
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//将权限放入shiro中
		info.addRoles(rolesList);
		info.addStringPermissions(permissionList);
		return info;
	}
	//认证、登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		SimpleAuthenticationInfo info = null;
		
		//获取用户输入的token
		UsernamePasswordToken utoken = (UsernamePasswordToken) token;
		String userId = utoken.getUsername();
/*		User user = new User();
		user.setUserPassword("d5102ad653ac919db2c76b47eb9366d4");
		user.setUserId("141006100");
		user.setUserPosition("驾校领导");
		user.setUserStatus("开启");
		user.setUserName("admin");
		user.setUserSex("男");
		user.setCampus("总部");
		user.setUserDept("人事部");*/
		User user = userService.findUserById(userId);
		//MD5加盐
		if(user != null){
			Object principal = user.getUserId();
			Object credentials = user.getUserPassword();
			System.out.println(credentials);
			ByteSource salt = ByteSource.Util.bytes(userId);
			info = new SimpleAuthenticationInfo(user, credentials, salt, this.getClass().getName());
		}
		
//		return new SimpleAuthenticationInfo(user, user.getUserPassword(), this.getClass().getName());
		return info;
	}

}
